<template>  
  <el-container class="height100 domainHeader mainContent bgColor" >
    <el-header class="obpm-header-t">
      <admin_header :desc="$t('enterprise_list')" :isCanExit="isCanExit"/>
    </el-header>
    <el-main v-show="showmode=='LIST'" class="mainHeight  padding0 whiteBgColor domainMainContent" ref="managerMain">
      <el-row ref="normalHeight">
       <header_item  :headerArr="headerArr"  @onBtnClick="onBtnClick" :multipleSelection="multipleSelection"/>
    </el-row>
      <el-row ref="search">
        <el-form :inline="true" class="searchForm" size="small"  @submit.native.prevent >
        <el-form-item >
          <el-input :placeholder="$t('enterprise_name')" v-model="searchdata.data.name" @keyup.enter.native="searchTableData"></el-input>
        </el-form-item>
        <el-form-item >
          <el-input type='text' :placeholder="$t('admin')" v-model="searchdata.data.username" @keyup.enter.native="searchTableData"></el-input>
        </el-form-item>
          <el-form-item class="paddingLeft0" v-for="elm in SupportSearchList" :key="elm.id" >
                <el-input v-model="searchdata.data.fieldExtends[elm.name]" :placeholder="elm.label" @keyup.enter.native="searchTableData"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchTableData" plain size="small">{{$t('query')}}</el-button>
          <el-button  @click="resetDomainSearch" size="small">{{$t('reset')}}</el-button>
        </el-form-item>
      </el-form>
      </el-row>
      <el-row :gutter="12" v-if="!showListVisible" v-loading="loading">
        <el-col v-for="domain in DomainDataFilter" :key="domain.id" :span="4">
          <el-card shadow="hover" class="domainList">
            <div class="domainLi">
              <el-row type="flex" class="row-bg" justify="end">
                <el-col :span="1" class="domainLiDel">
                  <i class="el-icon-close " @click="deleteDomain(domain.id)"></i>
                </el-col>
              </el-row>
              <router-link :to="{ name: 'domain', query: { domainid: domain.id, showLdapButton: showLdapButton, name: domain.name}}" class="FontColor">
                <el-row>
                  <el-col :span="6">
                    <div v-if="domain.logoUrl!=''">
                      <img :src="domain.logoUrl" class="domainLiImg" >
                    </div>
                    <div v-if="domain.logoUrl==''">
                      <!-- 4.4 与 5.0 加载不一样的logo -->
                      <img src="../assets/images/op.png" class="domainLiImgT5">
                    </div>
                  </el-col>
                  <el-col :span="18" >
                    <p><span  :title="domain.name" class="domainLiName">{{domain.name}}</span><span class="domainLiStatus">{{domain.status == 1 ? $t('activated') : $t('inactivated')}}</span></p>
                    <p class="domainLiAdmin">
                      <span v-for="(elm,index) in domain.users" :key="index">{{elm.username}},</span>
                    </p>
                    <p>
                      <!-- <el-switch class="miniFontSize" v-model="domain.status" @change="changeStatus(domain)" :active-value="1" :inactive-value="0"></el-switch> -->
                    </p>

                  </el-col>
                </el-row>
              <!-- <router-link :to="{ name: 'domain', query: { domainid: domain.id}}">{{domain.name}}</router-link>
              <el-button type="text" icon="el-icon-delete" style="float:right;vertical-align:middle" @click="deleteDomain(domain.id)"></el-button> -->
              </router-link>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6" v-if="!isAdminDomain ? domains.rowCount>=10 : DomainDataFilter.length>=10">
          <div class="adminListMore" @click="showList(true)">
            <img src="../assets/images/Arrow.png" alt="" class="adminListMoreImg">
          </div>
        </el-col>
      </el-row>
      <el-row  v-if="showListVisible">
        <el-table :data="DomainDataFilter"
        ref="multipleTable"
        :row-key="handleReserve"
        @row-click="onRowClick"
        class="Trpointer"
        @selection-change="handleSelectionChange"
        header-cell-class-name="tableHeaderbg"
        :height="tableListConHeight"
        size="small">
        <el-table-column type="selection" width="55" ></el-table-column>
        <el-table-column prop="name" :label="$t('enterprise_name')"></el-table-column>
        <el-table-column prop="users" :label="$t('admin')">
          <template slot-scope="scope">
            <span v-for="(elm,index) in scope.row.users" :key="index">
              {{elm.username}},
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="status" :label="$t('active')">
          <template slot-scope="scope">
            <span>{{scope.row.status==1?$t('active'):$t('inactive')}}</span>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      </el-row>
       <el-pagination
        v-if="showListVisible"
        @size-change="handleSizeChange"
        @current-change="searchTableData"
        :current-page.sync="searchdata.currpage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="searchdata.pagelines"
        layout="prev, pager, next, total, sizes"
        background
        class="paddingB0"
        :total="domains.rowCount?domains.rowCount:0"
        ref="pagination"
      ></el-pagination>
    </el-main>
    <!-- <div v-show="showmode=='DETAIL'" class="bgColor mainBg"> -->
      <main_detail  @exit="onExit" v-if="showmode=='DETAIL'"/>
    <!-- </div> -->
  </el-container>
</template>

<script>
import admin_header from "@/components/admin_header.vue";
import main_detail from "@/components/main_detail.vue";

export default {
  components: {
    admin_header,
    main_detail,
  },
  mounted(){
    this.tableListConHeight=this.$refs.managerMain.$el.getClientRects()[0].height-this.$refs.normalHeight.$el.getClientRects()[0].height-this.$refs.search.$el.getClientRects()[0].height-27-32;
  },
  created() {
    this.url=this.$api.getDebugUrl(this.url);
    this.searchTableData();
    // 如果是域管理员主页不可点击
    if(sessionStorage.getItem('onlyDomainUser')){
      this.isCanExit = false;
    }else{
      this.isCanExit = true;
    }
   if(this.$store.state.currentUser && this.$store.state.currentUser.isOpenSecurity) {
        if(this.$store.state.currentUser.domains.length>0) {
          this.isAdminDomain=true 
          this.adminDomainId=this.$store.state.currentUser.domains[0]
      }
    }
      let dataJson={ 
        currpage:1,
        pagelines:999,
        data:{
          belong: "All",
          fortable: "tableDomain",
          type: "",
        }
      }
    this.$api.getFieldExtends(
      dataJson,
      {
        onSucess: resp => {
          resp.data.data.datas.forEach(elm=>{
            if(elm.isSupportSearch){
              this.SupportSearchList.push(elm);
            }
          })
        }
      }
    );
    //关于标题的处理
    this.headerArr={iconfont:'icon-icon_yzh_off',content:this.$t('enterprise_list'),btnArr:[] }
  },
  watch:{
    isStatusShow(newVal,oldVal){
      if(newVal && this.headerArr.btnArr.length<3){
        this.headerArr.btnArr.unshift({type:'primary',name:"new",label:this.$t('new')})
      }
    }
  },
  computed:{
    //对返回的域数据根据三员管理条件渲染
    DomainDataFilter:function(){
      let temp=[]   
      if(!this.isAdminDomain ) return this.domains.datas
      if(this.domains.datas){
        this.domains.datas.forEach(e => {
        if((this.isAdminDomain && e.id==this.adminDomainId)){
          temp.push(e)
         }
       });
      }
      return temp
    }
  },
  data() {
    return {
      staticPath: this.$api.getStaticPath(),
      domains: [],
      searchUserName:'',
      showmode:'LIST',
      url:"/assets/images/LOGO.png",
      content:{},
      multipleSelection:[],
      searchdata:{
        currpage: 1,
        pagelines: 10,
        data:{
          name:"",
          username:'',
          fieldExtends: {}//扩展查询字段
        }
      },
      showListVisible:false,
      isStatusShow:false,
      showLdapButton: false,
      tableListConHeight:0,
      isCanExit: false,
      isAdminDomain:false,//是否是域级管理员
      adminDomainId:"",//记录域级id
      loading:false,//加载列表数据
      SupportSearchList:[],
      headerArr:{}
    };
  },

  methods: {
    onBtnClick(name){
      if(name=='new'){this.onCreateBtnClick()}
      else if(name=='del'){this.delDomain()}
      else if(name=='back'){this.exitDomainList()}
    },
    searchTableData(){
      let content=JSON.parse(JSON.stringify(this.searchdata))
      content.data.name=(content.data.name+"").trim()
      content.data.username=(content.data.username+"").trim()
      this.loading=true
      this.$api.getDomains(content,{
        onSucess: response => {
          this.loading=false
          console.log('reponse :',response.data)
          this.domains = response.data.data;
          this.isStatusShow=response.data.data.newButtonShow;
          this.showLdapButton = response.data.data.showLdapButton;
        }
      });
    },
    showList(value){
      let temp=[],tempArr=[]
      this.showListVisible=value;
      if(value){
        tempArr=[{type:'danger',name:"del",label:this.$t('del')},{name:"back",label:this.$t('back')}]
        temp=[...this.headerArr.btnArr,...tempArr]
      }else{
        if(this.headerArr.btnArr.length>=2){
          temp=JSON.parse(JSON.stringify(this.headerArr.btnArr))
          temp.splice(temp.length-2,2)
        }
      }
      this.$set(this.headerArr,"btnArr",temp)
    },
    changeStatus(domain){
      this.content=domain;
      this.$api.updateDomain(domain.id, this.content, {
          onSucess: resp => {
            if (resp && resp.data.errcode == 0) {
              this.$message({
                showClose: true,
                message: "修改成功!",
                type: "success"
              });
            } else {
              this.$message({
                message: resp.data.errmsg,
                type: "error"
              });
            }
          }
        });
    },
    onCreateBtnClick(){
       this.showmode = 'DETAIL';
    },
    
    resetDomainSearch(){
      this.searchdata={
        currpage: 1,
        pagelines: 10,
        data:{
          name:"",
          username:'',
          fieldExtends: {}
        }
      };
      this.searchTableData();
    },
    
    onExit(){
      this.showmode = 'LIST';
      this.searchTableData();
    },

    deleteDomain(domainid){
      this.delDomains([domainid])
    },
    delDomain(){
      if(this.multipleSelection.length > 0){
        this.delDomains(this.multipleSelection)
      }else{
        this.$message.error('请选择要删除的域')
      }
    },
    //退出域列表
    exitDomainList(){
      this.showList(false)
      this.searchdata={
        ...this.searchdata,
        currpage: 1,
        pagelines: 10,
      }
      this.searchTableData()
    },
    delDomains(ids){
      this.$api.deleteDomain( ids,  {
        onSucess: resp => {
          if(resp.data.errcode==0){
            this.$message({
              showClose: true,
              message: resp.data.data,
              type: "success"
            });
            this.searchTableData();
          }else{
            this.$message({
              showClose: true,
              message:resp.data.errmsg,
              type: "error"
            });
          }
        },
        onError:(resp) => {
          this.$message({
            showClose: true,
            message: resp.data.errmsg,
            type: "error"
          });
        }
      });
    },
    handleSelectionChange(val){
      var arr = [];
      val.map((val) => {
        this.domains.datas.map((v) => {
          if(val.id == v.id){
            arr.push(val.id)
          }
        })
      })   
      this.multipleSelection = arr;
    },
    handleReserve(row){
      return row.id
    },
    handleSizeChange(size){
      this.searchdata.pagelines=size;
      this.searchTableData();
    },
    onRowClick(row){
      this.$router.push({ name: 'domain', query: { domainid: row.id, name: row.name}})
    },
  }
};
</script>

<style>

</style>